package auctionServer.utilities;

import java.util.ArrayList;
import java.util.Collection;
import java.util.List;

public class GroupBid {

	private String bidder;
	private int auctionID;
	private int price;
	private List<String> confirms;
	private boolean isBidDone;
	private boolean bidResult;
	private byte[] bidResultResponse;
	
	public GroupBid(String bidder, int auctionID, int price){
		this.bidder=bidder;
		this.auctionID=auctionID;
		this.price=price;
		this.confirms=new ArrayList<String>();
		this.isBidDone=false;
	}
	
	public synchronized int getPrice(){
		
		return price;
	}
	
	public synchronized boolean addConfirm(String confirm, Collection<User> users, List<GroupBid> groupBids){
		boolean res = false;
		if (!confirm.equals(bidder)){
			for(String _confirm: confirms){
				if(confirm.equals(_confirm)){
					return false;
				}
			}
			
			//Preventing Deadlocks
			if (confirms.size() >= 1)
				res = true;
			else{
				int lockedUserCount = 1;
				for(GroupBid groupBid: groupBids){
					if (!groupBid.getIsBidDone()){
						if (groupBid.confirms.size() == 1)
							lockedUserCount++;
					}
				}
				int loggedInUsersCount = 0;
				for(User user: users){
					if (user.getValue())
						loggedInUsersCount++;
				}
				
				if (lockedUserCount < loggedInUsersCount)
					res = true;
			}
		}
		if (res)
			confirms.add(confirm);
		return res;
	}
	public synchronized void setPrice(int price){
		this.price = price;
	}
	public synchronized String getBidder(){
		return bidder;
	}
	
	public synchronized int getAuctionID(){
		return auctionID;
	}
	public synchronized int getConfirmCount(){
		return confirms.size();
	}
	public synchronized void setIsBidDone(boolean isBidDone){
		this.isBidDone = isBidDone;
	}
	public synchronized boolean getIsBidDone(){
		return isBidDone;
	}
	public synchronized void setBidResult(boolean bidResult){
		this.bidResult = bidResult;
	}
	public synchronized boolean getBidResult(){
		return bidResult;
	}
	public synchronized void setBidResultResponse(byte[] bidResultResponse){
		this.bidResultResponse = bidResultResponse;
	}
	public synchronized byte[] getBidResultResponse(){
		return bidResultResponse;
	}
	
}